#include "resizablerectscene.h"
#include "resizablerectitem.h"
#include <QGraphicsSceneMouseEvent>
#include <QKeyEvent>
#include <QDebug>

ResizableRectScene::ResizableRectScene(QObject *parent)
    : QGraphicsScene(parent),
      m_leftButtonDrawing(false),
      m_rightButtonDrawing(false),
      m_currentRect(nullptr),
      m_leftRect(nullptr),
      m_rightRect(nullptr)
{
    setBackgroundBrush(QBrush(Qt::white));
}

void ResizableRectScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    // 如果点击了已存在的项，让项处理事件
    if(event->button() == Qt::LeftButton){
        // 判断矩形是否存在且是否点击的是矩形内部，如果是交给子项处理
        if(m_leftRect && isPointInItem(m_leftRect,event->scenePos())){
            m_leftRect->setSelected(true);
            return QGraphicsScene::mousePressEvent(event);
        }
//        qDebug() << "未在矩形内部";

        m_startPoint = event->scenePos();
        if(!m_leftRect){
            m_leftRect = new ResizableRectItem(m_startPoint.x(), m_startPoint.y(), 0, 0);
            addItem(m_leftRect);
        }

        // 重新设置矩形大小
        m_leftRect->setRect(m_startPoint.x(), m_startPoint.y(), 0, 0);
        m_leftButtonDrawing = true;
        m_rightButtonDrawing = false;
    }

    // 场景自己处理了，不需要在交还了
//    QGraphicsScene::mousePressEvent(event);
}

void ResizableRectScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if (m_leftButtonDrawing && m_leftRect) {
        // 这样可以实现鼠标往坐上角进行拖动
        QPointF currentPoint = event->scenePos();
        qreal x = qMin(m_startPoint.x(), currentPoint.x());
        qreal y = qMin(m_startPoint.y(), currentPoint.y());
        qreal width = qAbs(currentPoint.x() - m_startPoint.x());
        qreal height = qAbs(currentPoint.y() - m_startPoint.y());
        m_leftRect->setRect(x, y, width, height);
    }

    QGraphicsScene::mouseMoveEvent(event);
}

void ResizableRectScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{

    if(m_leftButtonDrawing && m_leftRect){
        m_leftButtonDrawing = false;
        // 点击就是像素小于5x5那么从场景中移除
        QRectF rect = m_leftRect->rect();
        // 只有点击才会将资源释放【在从新添加的时候不释放不好判断如何添加】
        // 当点击矩形外部，然后拖动不会将资源释放，那时候只是将矩形大小置为特别小
        if(rect.width() < 5 && rect.height() < 5){
            removeItem(m_leftRect);
            delete m_leftRect;
            m_leftRect = nullptr; // 删了到时候可以从新添加
            return;
        }
        m_leftRect->setSelected(true);
    }

    QGraphicsScene::mouseReleaseEvent(event);
}

bool ResizableRectScene::isPointInItem(QGraphicsRectItem *targetItem, const QPointF &scenePos)
{
    if(!targetItem){
        return false;
    }
    // 将场景坐标转换为目标项内部的本地坐标
    QPointF localPos = targetItem->mapFromScene(scenePos);

    return targetItem->contains(localPos);

}
